var user_SystemStatus = function() {
    var monitorid, type, time, periods, sitename, vmMonitorStatus;
    var cpu_all = [],
    cpu_user = [],
    cpu_system = [],
    cpu_iowait = [],
    memory = [],
    network_in = [],
    network_out = [];
    
    function getUserMonitorVMs(callback) {
        for (var j = 0; j < allsites.length; j++) { (function(siteName) {
                $.get('/' + siteName + '/iaas/execute_wait_cacheable/iaas.get_vmpool_info.json?user_name=' + userid, {},
                function(serverResponse) {
                    var hostMachine;
                    var vmid;
                    var vmip;
                    var vmport;
                    var vmname;
                    var vcpus;
                    var memorysize;
                    var stat;
                    var starttime;
                    var tableData = [];
                    if (serverResponse[0] === false) {
                        return;
                    }
                    for (var i = 0; i < serverResponse[1].length; i += 1) {
                        vmid = serverResponse[1][i].guid;
                        vmname = serverResponse[1][i].name;
                        vmip = serverResponse[1][i].ip;
                        vmport = serverResponse[1][i].port;
                        vcpus = serverResponse[1][i].cpu;
                        memorysize = serverResponse[1][i].memory; //1024;
                        hostMachine = serverResponse[1][i].hostMachine;
                        stat = serverResponse[1][i].stat;
                        starttime = serverResponse[1][i].stime;
                        tableData.push([vmid, siteName, vcpus, memorysize, stat]);
                    }
                    callback(siteName, tableData);
                },
                'json');
            })(allsites[j]);
        }
    };

    function loadMonitorVMs(siteName, tableData) {
        for (var j = $('#userSystemStatusVMTable').dataTable().fnSettings().aoData.length - 1; j >= 0; j--) {
            var name = $('#userSystemStatusVMTable').dataTable().fnSettings().aoData[j]._aData[1];
            if (name == siteName) {
                var node = $('#userSystemStatusVMTable').dataTable().fnGetNodes(j);
                $('#userSystemStatusVMTable').dataTable().fnDeleteRow(node);
            }
        }
        $('#userSystemStatusVMTable').dataTable().fnAddData(tableData);
    };

    function getCpuInfoHistory(sitename, monitorid, type, periods, callback) {
        cpu_all = [];
        cpu_user = [];
        cpu_system = [];
        cpu_iowait = [];
        $.get('/' + sitename + '/iaas/execute_wait_cacheable/mon_getter.get_stats.json?hostId=' + monitorid + '&metricName=cpu_user&stat=' + type + '&startTime=' + periods, {},
        function(cpu_user_time) {
            cpu_user = cpu_user_time;
            $.get('/' + sitename + '/iaas/execute_wait_cacheable/mon_getter.get_stats.json?hostId=' + monitorid + '&metricName=cpu_system&stat=' + type + '&startTime=' + periods, {},
            function(cpu_system_time) {
                cpu_system = cpu_system_time;
                $.get('/' + sitename + '/iaas/execute_wait_cacheable/mon_getter.get_stats.json?hostId=' + monitorid + '&metricName=cpu_iowait&stat=' + type + '&startTime=' + periods, {},
                function(cpu_iowait_time) {
                    cpu_iowait = cpu_iowait_time;
                    $.get('/' + sitename + '/iaas/execute_wait_cacheable/mon_getter.get_stats.json?hostId=' + monitorid + '&metricName=cpu_usage&stat=' + type + '&startTime=' + periods, {},
                    function(cpu_usage_time) {
                        cpu_all = cpu_usage_time;
                        callback(cpu_all, cpu_user, cpu_system, cpu_iowait);
                    },
                    'json');
                },
                'json');
            },
            'json');
        },
        'json');
    };
    function getCpuInfoStatus(sitename, monitorid, type, cpu_all, cpu_user, cpu_system, cpu_iowait, callback) {
        $.get('/' + sitename + '/iaas/execute_wait_cacheable/mon_getter.get_stats.json?hostId=' + monitorid + '&metricName=cpu_user&stat=' + type, {},
        function(cpu_user_time) {
            if (cpu_user_time) {
                if (cpu_user[cpu_user.length - 1][0] < cpu_user_time[0][0]) {
                    cpu_user.push(cpu_user_time[0]);
                    if (cpu_user.length > 100) {
                        cpu_user.shift();
                    }
                }
            }
            $.get('/' + sitename + '/iaas/execute_wait_cacheable/mon_getter.get_stats.json?hostId=' + monitorid + '&metricName=cpu_system&stat=' + type, {},
            function(cpu_system_time) {
                if (cpu_system_time) {
                    if (cpu_system[cpu_system.length - 1][0] < cpu_system_time[0][0]) {
                        cpu_system.push(cpu_system_time[0]);
                        if (cpu_system.length > 100) {
                            cpu_system.shift();
                        }
                    }
                }
                $.get('/' + sitename + '/iaas/execute_wait_cacheable/mon_getter.get_stats.json?hostId=' + monitorid + '&metricName=cpu_iowait&stat=' + type, {},
                function(cpu_iowait_time) {
                    if (cpu_iowait_time) {
                        if (cpu_iowait[cpu_iowait.length - 1][0] < cpu_iowait_time[0][0]) {
                            cpu_iowait.push(cpu_iowait_time[0]);
                            if (cpu_iowait.length > 100) {
                                cpu_iowait.shift();
                            }
                        }
                    }
                    $.get('/' + sitename + '/iaas/execute_wait_cacheable/mon_getter.get_stats.json?hostId=' + monitorid + '&metricName=cpu_usage&stat=' + type, {},
                    function(cpu_usage_time) {
                        if (cpu_usage_time) {
                            if (cpu_all[cpu_all.length - 1][0] < cpu_usage_time[0][0]) {
                                cpu_all.push(cpu_usage_time[0]);
                                if (cpu_all.length > 100) {
                                    cpu_all.shift();
                                }
                            }
                        }
                        callback(cpu_all, cpu_user, cpu_system, cpu_iowait);
                    },
                    'json');
                },
                'json');
            },
            'json');
        },
        'json');
    };
    function drawCpuHistory(cpu_all, cpu_user, cpu_system, cpu_iowait) {
        var CpuOptions = {
            xaxis: {
                tickFormatter: function(val, axis) {
                    return new Date(val * 1000).toTimeString().split(' ')[0];
                }
            },
            yaxis: {
                tickFormatter: function(val, axis) {
                    return val.toFixed(axis.tickDecimals) + '%';
                }
            }
        };
        if (($("#userSystemStatusCPUGraph").width() !== 0) && ($("#userSystemStatusCPUGraph").height() !== 0)) {
            $.plot($("#userSystemStatusCPUGraph"), [{
                label: "cpu_all",
                data: cpu_all
            },
            {
                label: "cpu_user",
                data: cpu_user
            },
            {
                label: "cpu_system",
                data: cpu_system
            },
            {
                label: "cpu_iowait",
                data: cpu_iowait
            }], CpuOptions);
        }
    };
    function getMemInfoHistory(sitename, monitorid, type, periods, callback) {
        $.get('/' + sitename + '/iaas/execute_wait_cacheable/mon_getter.get_stats.json?hostId=' + monitorid + '&metricName=mem_usage&stat=' + type + '&startTime=' + periods, {},
        function(serverResponse) {
            memory = serverResponse;
            callback(serverResponse);
        },
        'json');
    };
    function getMemInfoStatus(sitename, monitorid, type, memory, callback) {
        $.get('/' + sitename + '/iaas/execute_wait_cacheable/mon_getter.get_stats.json?hostId=' + monitorid + '&metricName=mem_usage&stat=' + type, {},
        function(serverResponse) {
            if (serverResponse) {
                if (memory[memory.length - 1][0] < serverResponse[0][0]) {
                    memory.push(serverResponse[0]);
                    if (memory.length > 100) {
                        memory.shift();
                    }
                }
            }
            callback(memory);
        },
        'json');
    };
    function drawMemHistory(serverResponse) {
        var MemOptions = {
            xaxis: {
                tickFormatter: function(val, axis) {
                    return new Date(val * 1000).toTimeString().split(' ')[0];
                }
            },
            yaxis: {
                tickFormatter: function(val, axis) {
                    return val.toFixed(axis.tickDecimals) + '%';
                }
            }
        };
        if (($("#userSystemStatusMemoryGraph").width() !== 0) && ($("#userSystemStatusMemoryGraph").height() !== 0)) {
            $.plot($("#userSystemStatusMemoryGraph"), [{
                label: "memory",
                data: serverResponse
            }], MemOptions);
        }
    };
    function getNetInInfoHistory(sitename, monitorid, type, periods, callback) {
        $.get('/' + sitename + '/iaas/execute_wait_cacheable/mon_getter.get_stats.json?hostId=' + monitorid + '&metricName=bytes_in&stat=' + type + '&startTime=' + periods, {},
        function(serverResponse) {
            network_in = serverResponse;
            $.get('/' + sitename + '/iaas/execute_wait_cacheable/mon_getter.get_stats.json?hostId=' + monitorid + '&metricName=bytes_out&stat=' + type + '&startTime=' + periods, {},
            function(serverResponse) {
                network_out = serverResponse;
                callback(network_in, network_out);
            },
            'json');
        },
        'json');
    };
    function getNetInInfoStatus(sitename, monitorid, type, network_in, network_out, callback) {
        $.get('/' + sitename + '/iaas/execute_wait_cacheable/mon_getter.get_stats.json?hostId=' + monitorid + '&metricName=bytes_in&stat=' + type, {},
        function(serverResponse) {
            if (serverResponse) {
                if (network_in[network_in.length - 1][0] < serverResponse[0][0]) {
                    network_in.push(serverResponse[0]);
                    if (network_in.length > 100) {
                        network_in.shift();
                    }
                }
            }
            $.get('/' + sitename + '/iaas/execute_wait_cacheable/mon_getter.get_stats.json?hostId=' + monitorid + '&metricName=bytes_out&stat=' + type, {},
            function(serverResponse) {
                if (serverResponse) {
                    if (network_out[network_out.length - 1][0] < serverResponse[0][0]) {
                        network_out.push(serverResponse[0]);
                        if (network_out.length > 100) {
                            network_out.shift();
                        }
                    }
                }
                callback(network_in, network_out);
            },
            'json');
        },
        'json');
    };
    function drawNetHistory(network_in, network_out) {
        var NetworkOptions = {
            xaxis: {
                tickFormatter: function(val, axis) {
                    return new Date(val * 1000).toTimeString().split(' ')[0];
                }
            },
            yaxis: {
                tickFormatter: function(val, axis) {
                    if (val > 1048576) return (val / 1048576).toFixed(axis.tickDecimals) + 'MB/s';
                    else if (val > 1024) return (val / 1024).toFixed(axis.tickDecimals) + 'KB/s';
                    else return val.toFixed(axis.tickDecimals) + 'B/s';
                }
            }
        };
        if (($("#userSystemStatusNetworkGraph").width() !== 0) && ($("#userSystemStatusNetworkGraph").height() !== 0)) {
            $.plot($("#userSystemStatusNetworkGraph"), [{
                label: "network_in",
                data: network_in
            },
            {
                label: "network_out",
                data: network_out
            }], NetworkOptions);
        }
    };

    function plotUserSystemStatusGraphHistory() {
        if (($("#userSystemStatusCPUGraph").width() !== 0) && ($("#userSystemStatusCPUGraph").height() !== 0)) {
            $.plot($("#userSystemStatusCPUGraph"), [{
                label: "cpu",
                data: [[0, 0]]
            }]);
        }
        if (($("#userSystemStatusMemoryGraph").width() !== 0) && ($("#userSystemStatusMemoryGraph").height() !== 0)) {
            $.plot($("#userSystemStatusMemoryGraph"), [{
                label: "memory",
                data: [[0, 0]]
            }]);
        }
        if (($("#userSystemStatusNetworkGraph").width() !== 0) && ($("#userSystemStatusNetworkGraph").height() !== 0)) {
            $.plot($("#userSystemStatusNetworkGraph"), [{
                label: "network_in",
                data: [[0, 0]]
            }]);
        }
        if (periods == '15min') {
            periods = -900;
        }
        if (periods == '30min') {
            periods = -1800;
        }
        if (periods == '1h') {
            periods = -3600;
        }
        if (periods == '3h') {
            periods = -10800;
        }
        if (periods == '6h') {
            periods = -21600;
        }
        getCpuInfoHistory(sitename, monitorid, type, periods, drawCpuHistory);
        getMemInfoHistory(sitename, monitorid, type, periods, drawMemHistory);
        getNetInInfoHistory(sitename, monitorid, type, periods, drawNetHistory);
    };

    function plotUserSystemStatusGraph() {
        if (($("#userSystemStatusCPUGraph").width() !== 0) && ($("#userSystemStatusCPUGraph").height() !== 0)) {
            $.plot($("#userSystemStatusCPUGraph"), [{
                label: "cpu",
                data: [[0, 0]]
            }]);
        }
        if (($("#userSystemStatusMemoryGraph").width() !== 0) && ($("#userSystemStatusMemoryGraph").height() !== 0)) {
            $.plot($("#userSystemStatusMemoryGraph"), [{
                label: "memory",
                data: [[0, 0]]
            }]);
        }
        if (($("#userSystemStatusNetworkGraph").width() !== 0) && ($("#userSystemStatusNetworkGraph").height() !== 0)) {
            $.plot($("#userSystemStatusNetworkGraph"), [{
                label: "network_in",
                data: [[0, 0]]
            }]);
        }
 
        if (time == '15sec') {
            time = 15000;
        }
        if (time == '1min') {
            time = 60000;
        }
        if (time == '5min') {
            time = 300000;
        }
        var pretime = -1500;
        getCpuInfoHistory(sitename, monitorid, type, pretime, drawCpuHistory);
        getMemInfoHistory(sitename, monitorid, type, pretime, drawMemHistory);
        getNetInInfoHistory(sitename, monitorid, type, pretime, drawNetHistory);
        function fetchData() {
            getCpuInfoStatus(sitename, monitorid, type, cpu_all, cpu_user, cpu_system, cpu_iowait, drawCpuHistory);
            getMemInfoStatus(sitename, monitorid, type, memory, drawMemHistory);
            getNetInInfoStatus(sitename, monitorid, type, network_in, network_out, drawNetHistory);
        }
        vmMonitorStatus = setInterval(fetchData, time);

    };

    $("#userSystemStatusGraphIsRealtimeInput").click(function(event) {
        var seed = $(this)[0].checked;
        $("#userSsytemStatusGraphRealtime")[0].disabled = !seed;
        $("#userSsytemStatusGraphHistory")[0].disabled = seed;
    });
    $("#userSystemStatusDrawGraphButton").click(function(event) {
        var anSelected = fnGetSelected(userSystemStatusVMTable);
        var a = $('td', anSelected);
        if (a.length === 0) {
            alert("please select one row!");
            return 0;
        }
        monitorid = $(a[0]).text();
        sitename = $(a[1]).text();
        type = $("#userSsytemStatusGraphType")[0].value;
        time = $("#userSsytemStatusGraphRealtime")[0].value;
        periods = $("#userSsytemStatusGraphHistory")[0].value;
        $('#bottomInfoText').text($(a[1]).text() + ':' + $(a[0]).text());
        if ($("#userSsytemStatusGraphRealtime")[0].disabled === true) {
            clearInterval(vmMonitorStatus);
            plotUserSystemStatusGraphHistory();

        }
        else {
            clearInterval(vmMonitorStatus);
            plotUserSystemStatusGraph();
        }
    });
    $("#userSystemStatusRefreshTableButton").click(function(event) {
        getUserMonitorVMs(loadMonitorVMs);
    });
    getUserMonitorVMs(loadMonitorVMs);
};
